package oa.hleast.xswl.service.activity.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import oa.hleast.common.web.exception.BizException;
import oa.hleast.xswl.mapper.activity.CmsActivityTypeMapper;
import oa.hleast.xswl.pojo.domain.activity.CmsActivityType;
import oa.hleast.xswl.service.activity.ICmsActivityTypeService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
@Transactional
@AllArgsConstructor
public class CmsActivityTypeServiceImpl extends ServiceImpl<CmsActivityTypeMapper, CmsActivityType> implements ICmsActivityTypeService {

    @Override
    public CmsActivityType getByCode(String code) {
        List<CmsActivityType> list = this.list(new LambdaQueryWrapper<CmsActivityType>()
                .eq(CmsActivityType::getCode, code)
                .last("limit 1"));
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }

        log.info("list = {}", list);
        return list.get(0);
    }

    /**
     * 编码是否存在
     */
    public boolean isRepeatCode(String code) {
        int count = this.count(new LambdaQueryWrapper<CmsActivityType>()
                .eq(CmsActivityType::getCode, code)
                .last("limit 1")
        );

        if (count > 0) {
            return true;
        }

        return false;
    }

    @Override
    public boolean add(CmsActivityType form) {
        log.info("form = {}", form);
        if (isRepeatCode(form.getCode())) {
            throw new BizException("编码请保持唯一");
        }
        return this.save(form);
    }

    @Override
    public boolean update(CmsActivityType form) {
        Long id = form.getId();
        CmsActivityType activityType = this.getById(id);
        String oldCode = activityType.getCode();
        if (!oldCode.equals(form.getCode()) && isRepeatCode(form.getCode())) {
            throw new BizException("编码请保持唯一");
        }

        return this.updateById(form);
    }

    @Override
    public Page<CmsActivityType> pageList(Integer page, Integer limit, String typeName, Integer display) {
        return this.page(new Page<>(page, limit), new LambdaQueryWrapper<CmsActivityType>()
                .orderByDesc(CmsActivityType::getGmtCreate)
                .orderByDesc(CmsActivityType::getGmtModified)
        );
    }

    @Override
    public boolean deleteByIds(List<String> asList) {
        return this.removeByIds(asList);
    }

    @Override
    public CmsActivityType detail(Long id) {
        return this.getById(id);
    }
}
